package com.leetcode.dynamic_programming;

/**
 * @author Dennis Li
 * @date 2020/7/19 15:37
 */
public class NumArray {

    private int[] array;

    public NumArray(int[] nums) {
        int len = nums.length;
        // 只有在数组长度不为0的时候才会进行初始化
        if(len > 0){
            // 数组的大小为 len + 1而不是len，要进行闭区间的取值
            array = new int[len + 1];
            array[0] = nums[0];
            for (int j = 1; j < len + 1; j++)
                array[j] = array[j - 1] + nums[j - 1];
        }
    }

    public int sumRange(int i, int j) {
        // 闭区间,所以j + 1也需要取
        return array[j + 1] - array[i];
    }

    static class NumArray2 {

        private int[] pre;

        public NumArray2(int[] nums) {
            pre = new int[nums.length + 1];
            for (int i = 1; i <= nums.length; i++) {
                pre[i] = pre[i - 1] + nums[i - 1];
            }
        }

        public int sumRange(int i, int j) {
            return pre[j + 1] - pre[i];
        }

    }

}
